from PySide6.QtWidgets import QWidget,QTableWidgetItem,QMessageBox,QAbstractItemView,QHeaderView,QFileDialog
from numpy.distutils.command.egg_info import egg_info

from views.salary.setreform2006.setreform2006 import Ui_setreform6
from views.salary.setreform2006.setreformstatistics2006 import Ui_setreformstatistics
from views.person.model.person import PersonBaseInfo
from sqlalchemy.orm import Session
from settings.publicvar import engine
from views.salary.model.salary import Setreform,SetreformStatistics
import os,pandas as pd


class Setreform2006View(QWidget,Ui_setreform6):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.load_table_data()
        self.setreformtable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.setreformtable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setreformtable.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)

        self.calculatebtn.clicked.connect(self.calculateFun)
        self.serearchbtn.clicked.connect(self.serearchFun)

# 表格结构
    def setTableStructure(self, data):
        self.setreformtable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.setreformtable.setItem(i, 0, idx)
            name = QTableWidgetItem(item.personbase.name)
            self.setreformtable.setItem(i, 1, name)
            setreform_name = QTableWidgetItem(item.setreform_name)
            self.setreformtable.setItem(i, 2, setreform_name)
            position_number = QTableWidgetItem(item.position_number)
            self.setreformtable.setItem(i, 3, position_number)
            job_number = QTableWidgetItem(item.job_number)
            self.setreformtable.setItem(i, 4, job_number)
            salaryscale = QTableWidgetItem(item.salaryscale_number)
            self.setreformtable.setItem(i,5,salaryscale)
            mark = QTableWidgetItem(item.mark)
            self.setreformtable.setItem(i, 6, mark)

# 数据加载
    def load_table_data(self):
        with Session(engine) as session, session.begin():
            salaryscales = session.query(Setreform).all()
            self.setTableStructure(salaryscales)

    # 计算
    def calculateFun(self):
        print('计算')

    # 搜索
    def serearchFun(self):
        sereachdata = self.sereachedit.text().strip()
        if sereachdata == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.load_table_data()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.name.like('%' + sereachdata + '%')).all()
                sereachIDcard = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.like('%' + sereachdata + '%')).all()
                sereachiphone = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.iphone.like('%' + sereachdata + '%')).all()
                sereachpersonbase_type = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.person_type.like('%' + sereachdata + '%')).all()
                sereachData = sereachName + sereachIDcard + sereachiphone + sereachpersonbase_type
                others = []
                if sereachData != []:
                    for personbase in sereachData:
                        for other in personbase.setreforms:
                            others.append(other)
                    # 数据处理和加载QTable表
                    self.setTableStructure(others)
                else:
                    QMessageBox.critical(None,'没有数据','你搜索数据不存在！')


class SetfromStatistics2006View(QWidget,Ui_setreformstatistics):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.loadDataFun()
        self.serearchcom.currentTextChanged.connect(self.serearchFun)


    # 表格结构
    def setTableStructure(self, data):
        self.setreformstaticstable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.setreformstaticstable.setItem(i, 0, idx)
            position = QTableWidgetItem(item.position)
            self.setreformstaticstable.setItem(i, 1, position)
            position_year_start_number = QTableWidgetItem(str(item.position_year_start_number))
            self.setreformstaticstable.setItem(i, 2, position_year_start_number)
            position_year_end_number = QTableWidgetItem(str(item.position_year_end_number))
            self.setreformstaticstable.setItem(i, 3, position_year_end_number)
            job_year_start_number = QTableWidgetItem(str(item.job_year_start_number))
            self.setreformstaticstable.setItem(i, 4, job_year_start_number)
            job_year_end_number = QTableWidgetItem(str(item.job_year_end_number))
            self.setreformstaticstable.setItem(i, 5, job_year_end_number)
            salaryscale = QTableWidgetItem(str(item.salaryscale))
            self.setreformstaticstable.setItem(i, 6, salaryscale)
            mark = QTableWidgetItem(item.mark)
            self.setreformstaticstable.setItem(i, 7, mark)

    # 数据加载
    def load_table_data(self):
        with Session(engine) as session, session.begin():
            setreformstatistics = session.query(SetreformStatistics).all()
            self.setTableStructure(setreformstatistics)

    # 加载数据
    def loadDataFun(self):
        names = ['idx','position','position_year_start_number','position_year_end_number','job_year_start_number','job_year_end_number','salaryscale','mark']
        model_file_path = os.path.join('state', 'model', '2006年套改标准模板.xlsx')
        try:
            data = pd.read_excel(model_file_path,sheet_name=0,header=1,names=names).drop('idx', axis=1).to_dict('records')
            with Session(engine) as session,session.begin():
               setreformstatistics = session.query(SetreformStatistics).all()
               if not setreformstatistics:
                    setreformStatistics = [SetreformStatistics(**item) for item in data]
                    session.add_all(setreformStatistics)
        except:
            QMessageBox.critical(None, '导入失败', '数据加载失败！')
        self.load_table_data()

    # 搜索
    def serearchFun(self):
        serearchedit = self.serearchcom.currentText()
        with Session(engine) as session,session.begin():
            if serearchedit == '全部':
                self.load_table_data()
            else:
                data = session.query(SetreformStatistics).filter(SetreformStatistics.position == serearchedit).all()
                self.setTableStructure(data)
            QMessageBox.information(None,'成功','搜索%s岗位成功！'%serearchedit)